﻿using System;

namespace TakePhotoTogether.Communication.Protocols
{
    public class SlicedData : PayloadData
    {
        readonly int dataType;
        readonly int referId;
        readonly int packetIndex;
        readonly int totalNumberOfPackets;
        readonly byte[] slicedBytes = null;

        public int DataType
        {
            get { return dataType; }
        }

        public int ReferenceId
        {
            get { return referId;  }
        }

        public int PacketIndex
        {
            get { return packetIndex; }
        }

        public int NumberOfPackets
        {
            get { return totalNumberOfPackets; }
        }

        public byte[] SlicedBytes
        {
            get { return slicedBytes; }
        }

        private const int HEADER_SIZE = 7;

        public SlicedData(int messageType,
                          byte[] data,
                          int referenceId,
                          int index,
                          int numberOfPackets)
        {
            dataType = messageType;
            referId = referenceId;
            packetIndex = index;
            totalNumberOfPackets = numberOfPackets;

            slicedBytes = data;
        }

        public SlicedData(byte[] packetData)
        {
            if (packetData != null)
            {
                int dataSize = packetData.Length - HEADER_SIZE;
                slicedBytes = new byte[dataSize];

                dataType = (int)packetData[0];
                referId = BitConverter.ToInt32(packetData, 1);
                packetIndex = (int)packetData[5];
                totalNumberOfPackets = (int)packetData[6];

                for (int i = 0; i < dataSize; i++)
                {
                    slicedBytes[i] = packetData[i + HEADER_SIZE];
                }
            }
        }

        public byte[] ToBytes()
        {
            byte[] payloadData = new byte[slicedBytes.Length + HEADER_SIZE];

            payloadData[0] = (byte)dataType;

            byte[] referIdBytes = BitConverter.GetBytes(referId);

            for (int i = 0; i < 4; i++)
            {
                payloadData[i+1] = referIdBytes[i];
            }

            payloadData[5] = (byte)packetIndex;
            payloadData[6] = (byte)totalNumberOfPackets;

            for (int i = 0; i < slicedBytes.Length; i++)
            {
                payloadData[i + HEADER_SIZE] = slicedBytes[i];
            }

            return payloadData;
        }

    }
}
